/**
 * Created by tangting on 2017/12/5.
 */

import Vue from 'vue';
import tpl from './tpl.html';

import commonService from '../../../common/commonService';
import symbolConfig from '../../../common/symbolConfig';
import format from '../../../common/format';
import CONFIG from './config'

import Loading from '../../../../grsc-base/component/Loading.vue';
import NoData from '../../../../grsc-base/component/NoData.vue';

import filter from '../../../../grsc-base/util/filter';
import mathtool from '../../../../grsc-base/util/mathtool';
import lang from './lang';
import service from './service';
const SORT_UP = 'UP';
const SORT_DOWN = 'DOWN';

export default Vue.extend({
	name: "coins",
	template: tpl,
	components: {
		Loading,
		NoData
	},
	data() {
		return {
			symbolConfig: symbolConfig,

			lang: lang[this.$i18n.locale],
			isLoading: true,
			isActive: symbolConfig.MARKET_TABS.STANDRARD.LABEL,
			filter: filter,
			keyCoin: '',

			coinsMap: {}, // 存储所有币子的映射关系，如{BTC_ACT: {}, BTC_LTC: {}...}
			currentCoins: [],

			currentBtcPrice: '--',
			currentEthPrice: '--',
			currentActPrice: '--',
			currentUdcPrice: '--',

			CONFIG: CONFIG,
			forkCoins: null,

			currentSortKey: 'changeRatio', // 当前排序关键字，symbol, price, changeRatio, highPrice, lowPrice, cumulative, tradeFee
			currentSortOrder: SORT_DOWN, // 升序还是降序，默认降序

			SORT_UP,
			SORT_DOWN,
			MYCN:'',
			SORT_KEY: {
				symbol: 'symbol',
				price: 'price',
				changeRatio: 'changeRatio',
				highPrice: 'highPrice',
				lowPrice: 'lowPrice',
				cumulative: 'cumulative',
				tradeFee: 'tradeFee'
			},
			USDCNY: 6.70,
		}
	},
	created() {
		let that = this;
		this.getMYCN();
		$(document).off('$$USDCNY').on('$$USDCNY', (event, USDCNY) => {
			this.$USDCNY = USDCNY;
			this.$forceUpdate();
		});
		$.when(service.getConfigSymbolRank(), //获取币种排行
			//commonService.symbolList(),            // 币种的交易状态，上线、下线等
			commonService.symbolConfigList(), // 交易手续费
			// commonService.getBitfinexBtcPrice(),btcPriceRep,
			commonService.getTradeDetail()).done((symbolRep, symbolProfileRep,  detailRep) => {

			if (symbolRep.code !== window.CODE.SUCCESS) {
				window.error(symbolRep.msg);
				return;
			}

			if (symbolProfileRep.code !== window.CODE.SUCCESS) {
				window.error(symbolProfileRep.msg);
				return;
			}

			// if (btcPriceRep.code !== window.CODE.SUCCESS) {
			// 	window.error(btcPriceRep.msg);
			// 	return;
			// }

			let symbolList = symbolRep.data;
			let symbolProfileList = symbolProfileRep.data;

			// 1.合并数组，并且初始化 this.coinsMap
			initCoinsMap(symbolList, symbolProfileList);

			// 将整合之后的数据提供给其他组件进行使用
			$(document).trigger('$$price', [this.coinsMap]);

			// 2.进行分区
			// doSymbolMarkets(temps);

			// 3. 获取BTC的价格
			// doBtcRep(btcPriceRep);

			// 4. 展示价格
			doDetailRep(detailRep);

			// 5. 循环价格
			that._loopTradeDetail();

		});

		function initCoinsMap(symbolList, symbolProfileList) {
			let innerObj;

			$.map(symbolList, (item, index) => {

				for (let i = 0; i < symbolProfileList.length; i++) {
					innerObj = symbolProfileList[i];

					if (item.symbol === innerObj.symbol) {
						item[innerObj.profileKey] = innerObj.profileValue;
					}
				}
			});

			$.map(symbolList, (item, index) => {
				// item.SHOWSTATUS === 'ON'的选项
				if (item.SHOWSTATUS === 'ON') {
					that.coinsMap[item.symbol] = item;
				}
			});

		}

		function doBtcRep(rep) {
			if (rep.code === window.CODE.SUCCESS) {
				that.currentBtcPrice = rep.data.last_price;
			}
		}

		function doDetailRep(rep) {
			that._doResult(rep)
		}

	},
	mounted() {
		this.formatPrice('0.0000232');
	},
	methods: {
		getMYCN() {
			commonService.getTradeDetail().done((rep) => {
				this.MYCN = rep['USDT_MYCN'].newPrice;
			})
		},
		goPage(item) {
			if (item.status !== 'INIT') {
				window.location.href = './market.html?s=' + (item.assetCode2 + '_' + item.assetCode1);
			}
		},

		/**
		 *
		 * @param key
		 */
		sortByKey(key) {
			// 新排序
			if (this.currentSortKey !== key) {
				this.currentSortKey = key;
				if (this.currentSortKey !== 'symbol') {
					this.currentSortOrder = SORT_DOWN; // 默认降序
				} else {
					this.currentSortOrder = SORT_UP;
				}
			} else {
				if (this.currentSortOrder === SORT_UP) {
					this.currentSortOrder = SORT_DOWN;
				} else {
					this.currentSortOrder = SORT_UP;
				}
			}
			this._doCurrentCoins();
		},

		_resetSort() {
			this.currentSortKey = '';
			this.currentSortOrder = '';
		},

		/**
		 * 处理目前需要展示的币种列表
		 * @private
		 */
		_doCurrentCoins() {
			let tempArr = [];
			let results = [];

			//   if (this.isActive !== symbolConfig.MARKET_TABS.USD.LABEL) {
			$.map(this.coinsMap, (item, key) => {
				if (item.region === this.isActive) {
					tempArr.push(item);
				}
			});
			// } else {
			//     $.map(this.coinsMap, (item, key) => {
			//         if (item.assetCode1 === 'USC' || item.assetCode1 === 'USDT') {
			//             tempArr.push(item);
			//         }
			//     });
			// }


			// 进行排序

			let key = this.currentSortKey;
			if (key) {
				if (key === 'symbol') {
					results = insertSortStr(tempArr, key, this.currentSortOrder);
				} else {
					results = insertSortNum(tempArr, key, this.currentSortOrder);
				}
			} else {
				results = tempArr;
			}
			this.currentCoins = results;
			this.currentCoins.sort(function(a,b){
                return b.rank-a.rank;
            })
			$.map(this.currentCoins, (item, key) => {
				
				let data = {
				asset : item.assetCode2
				};
				service.getIconList(data).done(rep => {
				  if (rep.data) {
					item.img = rep.data[0].newfilename;
				  } else {
					item.img = "";
				  }
				});
			  });

			//数组预处理
			function preArrayOperate(array) {
				let liuArray = [];
				let arr1 = []
				let arr2 = []
				for (var j = 0; j < array.length; j++) {
					if (array[j].rank !== 0) {
						arr1.push(tempArr[j])
					} else {
						arr2.push(tempArr[j])
					}
				}

				arr1 = arr1.sort((a, b) => {
					return parseInt(a.rank) - parseInt(b.rank)
				})
				// for (var i = 0; i < arr2.length; i++) {
				// 	arr1.push(arr2[i])
				// }
				for (let i = 0; i < arr1.length; i++) {
					for (let j = 0; j < array.length; j++) {
						if (array[j].assetCode2 == arr1[i].assetCode2) {
							liuArray.push(array[j]);
							array.splice(j, 1)
							continue;
						}
					}
				}
				for (let i = 0; i < liuArray.length; i++) {
					if (liuArray[i] == undefined || liuArray[i] == null) {
						liuArray.splice(i, 1);
						i--;
					}
				}
				return liuArray;
			}

			function insertSortNum(array, key, sortBy) {
				let liuArray = [];
				liuArray = preArrayOperate(array);
				console.log(liuArray)
				/*start根据已排列好的项数决定*/
				let start = 0;
				let num1;
				let num2;
				/*按顺序，每一项检查已排列好的序列*/
				for (let i = start; i < array.length; start++, i++) {
					/*跟已排好序的序列做对比，并插入到合适的位置*/
					for (let j = 0; j < start; j++) {
						num1 = parseFloat(array[i][key]);
						num2 = parseFloat(array[j][key]);
						/*小于或者等于时（我们是升序）插入到该项前面*/
						if (num1 <= num2) {
							array.splice(j, 0, array[i]);
							/*删除原有项*/
							array.splice(i + 1, 1);
							break;
						}
					}

				}
				if (sortBy === SORT_DOWN) {
					array.reverse();
				}
				if (liuArray.length != 0) {
					return liuArray.concat(array);
				}
				return array
			}

			function insertSortStr(array, key, sortBy) {
				let liuArray = [];
				liuArray = preArrayOperate(array);
				/*start根据已排列好的项数决定*/
				let start = 0;
				/*按顺序，每一项检查已排列好的序列*/
				for (let i = start; i < array.length; start++, i++) {
					/*跟已排好序的序列做对比，并插入到合适的位置*/
					for (let j = 0; j < start; j++) {
						/*小于或者等于时（我们是升序）插入到该项前面*/
						if (array[i][key] <= array[j][key]) {
							array.splice(j, 0, array[i]);
							/*删除原有项*/
							array.splice(i + 1, 1);
							break;
						}
					}

				}
				if (sortBy === SORT_DOWN) {
					array = array.reverse();
				}
				// log(array);
				if (liuArray.length != 0) {
					return liuArray.concat(array);
				}
				return array
			}

			function log(list) {
				$.map(list, (item, index) => {});
			}

		},

		_doResult(rep) {
			this.isLoading = false;
			if (rep) {
				let arr = rep;
				if ($.isNumeric(this.currentBtcPrice) === true) {
					this.currentEthPrice = rep['BTC_ETH'] && mathtool.multiplication(rep['BTC_ETH'].newPrice, this.currentBtcPrice);
					this.currentActPrice = rep['BTC_ACT'] && mathtool.multiplication(rep['BTC_ACT'].newPrice, this.currentBtcPrice);
					this.currentUdcPrice = rep['BTC_UDC'] && mathtool.multiplication(rep['BTC_UDC'].newPrice, this.currenBtcPrice);
				}
				/*
				    if ($.isNumeric(this.currentUdcPrice) === true) {
				        this.currentEthPrice = rep['UDC_ETH'] && mathtool.multiplication(rep['UDC_ETH'].newPrice, this.currentUdcPrice);
				        this.currentMoacPrice = rep['UDC_MOAC'] && mathtool.multiplication(rep['UDC_MOAC'].newPrice, this.currentUdcPrice);
				        this.currentCfcPrice = rep['UDC_CFC'] && mathtool.multiplication(rep['UDC_CFC'].newPrice, this.currentUdcPrice);

				    }
				    */
				$.map(this.coinsMap, (item, key) => {
					if (!arr.hasOwnProperty(item.symbol)) {
						return;
					}
					console.log(this.coinsMap)
					let price;
					item.price = filter.floorFixPrice(arr[item.symbol]['newPrice'], item[symbolConfig.PRICEPRECISION]);

					if ($.isNumeric(this.currentBtcPrice)) {
						if (key.split('_')[0] === 'BTC' && $.isNumeric(this.currentBtcPrice) === true) {
							price = mathtool.multiplication(item.price, this.currentBtcPrice);
						} else if (key.split('_')[0] === 'USC' || key.split('_')[0] === 'USDT') {
							price = filter.floorFixPrice(item.price, 2);
						} else if (key.split('_')[0] === 'ETH' && $.isNumeric(this.currentEthPrice) === true) {
							price = mathtool.multiplication(item.price, this.currentEthPrice);
						} else if (key.split('_')[0] === 'ACT' && $.isNumeric(this.currentActPrice) === true) {
							price = mathtool.multiplication(item.price, this.currentActPrice);
						} else if (key.split('_')[0] === 'UDC') {
							//   price = mathtool.multiplication(item.price, this.currentUdcPrice);
							// price = filter.floorFixPrice(item.price, 2);
							price = item.price;
						}  else if (key.split('_')[0] === 'MYCN') {
							price = mathtool.multiplication(item.price, this.MYCN);
						}else {
							price = item.price;
						}
						item.priceUSD = filter.floorFixPrice(price, 4);
						console.log(this.$USDCNY)
						let CURRENCY_RMB = key.split('_')[0] === 'UDC' ? this.CURRENCY_RMB : this.$USDCNY
						item.priceRMB = filter.floorFixPrice(mathtool.multiplication(price, CURRENCY_RMB), 4);
					} else {
						item.priceUSD = '--';
						item.priceRMB = '--';
					}

					//最高价
					item.highPrice = filter.floorFixPrice(arr[item.symbol]['24high'], item[symbolConfig.PRICEPRECISION]);

					//最低价
					item.lowPrice = filter.floorFixPrice(arr[item.symbol]['24low'], item[symbolConfig.PRICEPRECISION]);

					//累计
					item.cumulative = filter.floorFix(arr[item.symbol]['24Total'], item[symbolConfig.AMOUNTPRECISION]);


					let pr_ne = arr[item.symbol]['newPrice']; // 最新價
					let pr_op = arr[item.symbol]['24Price']; // 開盤價
					// 漲跌幅
					let distance = pr_ne - pr_op;
					let symbol = '';
					if (distance < 0) {
						symbol = '-'
					} else if (distance > 0) {
						symbol = '+'
					}
					if (arr[item.symbol]['24Price'] == 0) {
						item.changeRatio = filter.floorFix(0, 2);
					} else {
						item.changeRatio = filter.floorFix(symbol + (filter.abs(distance) / pr_op * 100), 2);
					}
					item.changeRatioNum = parseFloat(item.changeRatio);
				});

				this._doCurrentCoins();

			}
		},
		fetchTradeFee() {
			commonService.getTradeFee({
				key: 'ASSETFEERATE'
			}).done(rep => {
				let arr;
				if (rep.code === window.CODE.SUCCESS) {
					arr = rep.data;
					$.map(arr, (item, index) => {
						if (item.symbol === 'BTC_TIC') {
							// this.coins['BTC_TV'].tradeFee = item.profileValue;
							// this.coins['BTC_TV'].tradeFeeText = mathtool.multiplication(item.profileValue, 100);
						} else {
							if (this.coins[item.symbol]) {
								this.coins[item.symbol].tradeFee = item.profileValue;
								this.coins[item.symbol].tradeFeeText = mathtool.multiplication(item.profileValue, 100);
							}
						}
					});
				}
			});
		},


		fetchTradeOpenStatus() {
			commonService.symbolList().done(rep => {
				let arr;
				if (rep.code === window.CODE.SUCCESS) {
					arr = rep.data;
					$.map(arr, (item, index) => {
						if (item.symbol === 'BTC_TIC') {
							// this.coins['BTC_TV'].status = item.status;
						} else {
							if (this.coins[item.symbol]) {
								this.coins[item.symbol].status = item.status;
							}
						}
					});
				}
			})
		},

		/**
		 *
		 * @param currentTab
		 */
		changeTab(currentTab) {
			this.keyCoin = '';
			if (this.isActive !== currentTab) {
				this.isActive = currentTab;
				this._resetSort();
				// this._doCurrentCoins();
				this.sortByKey('changeRatio');
			}
		},

		_loopTradeDetail() {
			let that = this;
			commonService.onLoopGetTradeDetail(rep => {
				that._doResult(rep);
			});
		},

		/**
		 * 从左往右第一个不为0的数开始置黑
		 * @param money
		 */
		formatPrice(money) {
			if ($.isNumeric(money) === false) {
				return money;
			}
			money = format.formatZeroSuffix(filter.floorFixPrice(money, 8), 8);

			let i = 0;
			for (i = 0; i < money.length; i++) {
				if (money[i] !== '0' && money[i] !== '.')
					break;
			}
			let suffix = money.substring(0, i);
			let prefix = money.substring(i);
			// let index = money.indexOf('.');
			// let prefix = money.substring(0, index);
			// let suffix = money.substring(index + 1);
			return '<em class="em">' + suffix + '</em><span class="strong">' + prefix + '</span>';
		},
		/**
		 * 整数部分置黑
		 * @param money
		 */
		formatMoney(money) {
			if ($.isNumeric(money) === false) {
				return money;
			}
			money = format.formatZeroSuffix(filter.floorFixPrice(money, 8), 8);
			let index = money.indexOf('.');
			let prefix = money.substring(0, index);
			let suffix = money.substring(index + 1);
			return '<span class="strong">' + prefix + '. </span><em class="em">' + suffix + '</em>';
		}

	}
});